package gui;

import fs.DBConfig;
import fs.Data;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 *
 * @author lucifer
 */
public class DBConfigDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private Frame parent;
  private DBConfig db;

  public DBConfigDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    this.parent = parent;
    initComponents();

    initConfig();

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

	private void initConfig() {
    db = new DBConfig("localhost", "5432", "postgres", "1234", "senzu");
		try {
			db = (DBConfig) Data.ReadFrom(Data.DB_SETTINGS);
		}
		catch (Exception e) {
		}
    ipjTextField.setText(db.IP);
    portjTextField.setText(db.PORT);
    userjTextField.setText(db.USR);
    passwordjPasswordField.setText(db.PASSWD);
    dbnamejTextField.setText(db.DBNAME);
	}

  private void setDefaults() {
    ipjTextField.setText("localhost");
    portjTextField.setText("5432");
    userjTextField.setText("postgres");
    passwordjPasswordField.setText("1234");
    dbnamejTextField.setText("senzu");
  }

  @SuppressWarnings("deprecation")
  private void saveConfig() {
    db.IP = ipjTextField.getText();
    db.PORT = portjTextField.getText();
    db.USR = userjTextField.getText();
    db.PASSWD = passwordjPasswordField.getText();
    db.DBNAME = dbnamejTextField.getText();
    
    try {
      Data.WriteObjectTo(db, Data.DB_SETTINGS);
    } catch (Exception e) {
      System.out.printf("?can't save db config\n");
    }

    JOptionPane.showMessageDialog(parent, "La configuración se actualizó correctamente. La aplicación debe reiniciarse y se cerrará.\nPor favor, vuelva a ejecutar Senzu manualmente.", "Éxito!", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    cancelButton = new javax.swing.JButton();
    ipjLabel = new javax.swing.JLabel();
    portjLabel = new javax.swing.JLabel();
    userjLabel = new javax.swing.JLabel();
    passwordjLabel = new javax.swing.JLabel();
    ipjTextField = new javax.swing.JTextField();
    portjTextField = new javax.swing.JTextField();
    userjTextField = new javax.swing.JTextField();
    passwordjPasswordField = new javax.swing.JPasswordField();
    defaultsjButton = new javax.swing.JButton();
    dbnamejTextField = new javax.swing.JTextField();
    dbnamejLabel = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Configuración de la Base de Datos");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Aceptar");
    okButton.setMaximumSize(new java.awt.Dimension(120, 27));
    okButton.setMinimumSize(new java.awt.Dimension(120, 27));
    okButton.setPreferredSize(new java.awt.Dimension(120, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelButton.setText("Cancelar");
    cancelButton.setMaximumSize(new java.awt.Dimension(120, 27));
    cancelButton.setMinimumSize(new java.awt.Dimension(120, 27));
    cancelButton.setPreferredSize(new java.awt.Dimension(120, 27));
    cancelButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelButtonActionPerformed(evt);
      }
    });

    ipjLabel.setText("Dirección IP");

    portjLabel.setText("Port");

    userjLabel.setText("User");

    passwordjLabel.setText("Password");

    ipjTextField.setText("localhost");
    ipjTextField.setMaximumSize(new java.awt.Dimension(255, 27));
    ipjTextField.setMinimumSize(new java.awt.Dimension(255, 27));
    ipjTextField.setPreferredSize(new java.awt.Dimension(255, 27));
    ipjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        ipjTextFieldFocusGained(evt);
      }
    });

    portjTextField.setText("5432");
    portjTextField.setMaximumSize(new java.awt.Dimension(255, 27));
    portjTextField.setMinimumSize(new java.awt.Dimension(255, 27));
    portjTextField.setPreferredSize(new java.awt.Dimension(255, 27));
    portjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        portjTextFieldFocusGained(evt);
      }
    });

    userjTextField.setText("postgres");
    userjTextField.setMaximumSize(new java.awt.Dimension(255, 27));
    userjTextField.setMinimumSize(new java.awt.Dimension(255, 27));
    userjTextField.setPreferredSize(new java.awt.Dimension(255, 27));
    userjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        userjTextFieldFocusGained(evt);
      }
    });

    passwordjPasswordField.setText("1234");
    passwordjPasswordField.setMaximumSize(new java.awt.Dimension(255, 27));
    passwordjPasswordField.setMinimumSize(new java.awt.Dimension(255, 27));
    passwordjPasswordField.setPreferredSize(new java.awt.Dimension(255, 27));
    passwordjPasswordField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        passwordjPasswordFieldFocusGained(evt);
      }
    });

    defaultsjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/defaults.png"))); // NOI18N
    defaultsjButton.setText("Defaults");
    defaultsjButton.setMaximumSize(new java.awt.Dimension(120, 27));
    defaultsjButton.setMinimumSize(new java.awt.Dimension(120, 27));
    defaultsjButton.setPreferredSize(new java.awt.Dimension(120, 27));
    defaultsjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        defaultsjButtonActionPerformed(evt);
      }
    });

    dbnamejTextField.setText("senzu");
    dbnamejTextField.setMaximumSize(new java.awt.Dimension(255, 27));
    dbnamejTextField.setMinimumSize(new java.awt.Dimension(255, 27));
    dbnamejTextField.setPreferredSize(new java.awt.Dimension(255, 27));
    dbnamejTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        dbnamejTextFieldFocusGained(evt);
      }
    });

    dbnamejLabel.setText("Base de datos");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(ipjLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(ipjTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(portjLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(portjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addGroup(layout.createSequentialGroup()
                    .addComponent(defaultsjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(dbnamejLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(dbnamejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
              .addContainerGap()
              .addComponent(userjLabel)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(userjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(passwordjLabel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(passwordjPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addContainerGap())
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(ipjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(ipjLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(portjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(portjLabel))
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(dbnamejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(dbnamejLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(userjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(userjLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(passwordjPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(passwordjLabel))
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(defaultsjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      doClose(RET_OK);
      saveConfig();
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

  private void defaultsjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultsjButtonActionPerformed
    setDefaults();
  }//GEN-LAST:event_defaultsjButtonActionPerformed

  private void ipjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ipjTextFieldFocusGained
    ipjTextField.selectAll();
  }//GEN-LAST:event_ipjTextFieldFocusGained

  private void portjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_portjTextFieldFocusGained
    portjTextField.selectAll();
  }//GEN-LAST:event_portjTextFieldFocusGained

  private void userjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_userjTextFieldFocusGained
    userjTextField.selectAll();
  }//GEN-LAST:event_userjTextFieldFocusGained

  private void passwordjPasswordFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_passwordjPasswordFieldFocusGained
    passwordjPasswordField.selectAll();
  }//GEN-LAST:event_passwordjPasswordFieldFocusGained

  private void dbnamejTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dbnamejTextFieldFocusGained
    dbnamejTextField.selectAll();
  }//GEN-LAST:event_dbnamejTextFieldFocusGained
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton cancelButton;
  private javax.swing.JLabel dbnamejLabel;
  private javax.swing.JTextField dbnamejTextField;
  private javax.swing.JButton defaultsjButton;
  private javax.swing.JLabel ipjLabel;
  private javax.swing.JTextField ipjTextField;
  private javax.swing.JButton okButton;
  private javax.swing.JLabel passwordjLabel;
  private javax.swing.JPasswordField passwordjPasswordField;
  private javax.swing.JLabel portjLabel;
  private javax.swing.JTextField portjTextField;
  private javax.swing.JLabel userjLabel;
  private javax.swing.JTextField userjTextField;
  // End of variables declaration//GEN-END:variables

  private int returnStatus = RET_CANCEL;
}
